package com.suitsoft.bdms.util;

import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
import java.util.Map;

import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;

/**
 * Excel工具类.
 *  
 * @author coombe
 */
public class ExcelUtils {
	
	private ExcelUtils() {
	}
	
	/**
	 * 输出数据到Excel文件.
	 * 
	 * @param titles	列标题
	 * @param keys		列标识
	 * @param dataList	数据集合
	 * @param os		输出数据流
	 * @throws IOException
	 * @throws WriteException
	 */
	public static synchronized  void expExcelResult(String[] titles, String[] keys
			, List<Map<String, Object>> dataList, OutputStream os) throws IOException, WriteException {
		// 然后将结果集转化为Excel输出
		// 初始化工作
		WritableWorkbook wwb = null;

		try {
			wwb = Workbook.createWorkbook(os);
			// 创建工作表
			jxl.write.WritableSheet ws = wwb.createSheet("Sheet1", 0);
			// 添加标题
			for (int col = 0; col < titles.length; col++) {
				ws.addCell(new Label(col, 0, titles[col]));
			}

			String s = "";
			Object obj = null;
			Map<String, Object> map;
			// 逐行添加数据
			for (int row = 0, rows = dataList.size(); row < rows; row++) {
				map = dataList.get(row);
				for(int col = 0, cols = titles.length; col < cols; col ++) {
					obj = map.get(keys[col]);
					if (obj == null) {
						s = "";
					} else {
						if (obj instanceof java.util.Date) {
							s = DateUtils.toString((java.util.Date) obj);
						} else {
							s = String.valueOf(obj);
						}
					}
					
					ws.addCell(new Label(col, row + 1, s));
				}
			}
		} finally {
			if (wwb != null) {
				wwb.write();
				wwb.close();
			}
		}
	}
}
